package etnorservice.etnor_service.service.impl;

import etnorservice.etnor_service.converter.ArticleConverter;
import etnorservice.etnor_service.domain.po.*;
import etnorservice.etnor_service.domain.response.CreateBlogParmResponse;
import etnorservice.etnor_service.domain.vo.ArticleVO;
import etnorservice.etnor_service.mapper.ArticleMapper;
import etnorservice.etnor_service.mapper.UserMapper;
import etnorservice.etnor_service.mapper.WorkspaceTreeMapper;
import etnorservice.etnor_service.request.ArticleRequest;
import etnorservice.etnor_service.request.BlogCreateRequest;
import etnorservice.etnor_service.service.ArticleService;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.*;

/**
 * Created with IntelliJ IDEA.
 *
 * @Author: cc
 * @Date: 2024/10/14/17:28
 **/
@Service
public class ArticleServiceImpl implements ArticleService {
    @Autowired
    ArticleMapper articleMapper;
    @Autowired
    WorkspaceTreeMapper workspaceTreeMapper;
    @Autowired
    UserMapper userMapper;
    @Value("${file.upload-dir}")
    private String uploadDir;
    @Override
    public List<ArticleVO> articleList() {
        List<BaseArticle> articleList=articleMapper.findArticleList();
        List<ArticleVO> articleVOList=new ArrayList<>();
        for(BaseArticle baseArticle:articleList){
            ArticleVO articleVO=new ArticleVO();
            articleVO= ArticleConverter.convert(baseArticle);
            articleVO.
                    setAuthorName(
                            userMapper.
                                    findRoleByAccount(Integer.parseInt(baseArticle.getAuthorId())).getUsername());
            articleVOList.add(articleVO);
        }




        return articleVOList;
    }

    @Override
    public ArticleVO findArticleById(String articleId,String language) {
        BaseArticle articleById = articleMapper.findArticleById(articleId,language);
        ArticleVO articleVO=
                ArticleConverter.convert(articleById);

        articleVO.
                setAuthorName(
                        userMapper.
                                findRoleByAccount(Integer.parseInt(articleById.getAuthorId())).getUsername());

        return articleVO;
    }

    @Override
    public void saveArticle(String id, String content,String language) throws IOException {
        // 解析HTML内容
        Document doc = Jsoup.parse(content);
        Elements imgElements = doc.select("img[src^=data:image]");

        // 保存图片
        List<String> imageUrls = new ArrayList<>();
        for (Element imgElement : imgElements) {
            String src = imgElement.attr("src");
            if (src.startsWith("data:image")) {
                byte[] imageData = Base64.getDecoder().decode(src.split(",")[1]);
                String fileName = "image_" + System.currentTimeMillis() + ".png";
                String imgUrl=uploadDir + "/" + fileName;
                File imageFile = new File(imgUrl);
                Files.write(imageFile.toPath(), imageData);

                String correctedSrc = imgUrl.replace("\\", "/");

                String newUrl = "http://localhost:8090/resources/docImgs/"+fileName;

                System.out.println("图片地址"+newUrl);
                // 更新图片URL
                imgElement.attr("src", newUrl);
                imageUrls.add(newUrl);
            }
        }

        // 更新HTML内容
        String updatedContent = doc.html();

        // 创建Article对象

        BaseArticle article = new BaseArticle();
        article.setArticleId(id);
        article.setContent(updatedContent);
        article.setLanguage(language);
        articleMapper.updateArticle(article);

        System.out.println("-------文件保存"+article);


    }

    @Override
    public List<ArticleVO> findArticleByIdAndAccount(String authorId,String spaceId) {
        List<BaseArticle> articleList=articleMapper.findArticleByIdAndAccount(authorId,spaceId);
        List<ArticleVO> articleVOList=new ArrayList<>();
        for(BaseArticle baseArticle:articleList){
            ArticleVO articleVO=new ArticleVO();
            articleVO= ArticleConverter.convert(baseArticle);
            articleVO.
                    setAuthorName(
                            userMapper.
                                    findRoleByAccount(Integer.parseInt(baseArticle.getAuthorId())).getUsername());
            articleVOList.add(articleVO);
        }




        return articleVOList;
    }

    @Override
    public CreateBlogParmResponse findBaseParams(String accountId) {
        CreateBlogParmResponse createBlogParmResponse=new CreateBlogParmResponse();
        createBlogParmResponse.setBlogTags(articleMapper.findAllTags());
        createBlogParmResponse.setVisibilities(articleMapper.findVisibilities());
        createBlogParmResponse.setBlogLinks(articleMapper.findBlogLinks(accountId));



        return createBlogParmResponse;
    }

    @Override
    public void addBlogs(BlogCreateRequest blogCreateRequest) {
        String articleId = UUID.randomUUID().toString();

        List<String> blogLinks = blogCreateRequest.getSelectedRelatedArticles();
        List<String> blogTags = blogCreateRequest.getSelectedTags();
        String copyright = blogCreateRequest.getCopyright();
        String visibility = blogCreateRequest.getVisibility();

        blogLinks.stream()
                .filter(link -> !link.isEmpty())
                .forEach(link -> articleMapper.addBlogLinks(link, articleId));

        blogTags.stream()
                .filter(tag -> !tag.isEmpty())
                .forEach(tag -> articleMapper.addBlogTags(tag, articleId));

        if (copyright != null && !copyright.isEmpty()) {
            articleMapper.addBlogCopiright(copyright, articleId);
        }

        if (visibility != null && !visibility.isEmpty()) {
            articleMapper.addBlogVisibale(visibility, articleId);
        }
        BaseArticle baseArticle=new BaseArticle();
        baseArticle.setArticleId(articleId);
        baseArticle.setTitle(blogCreateRequest.getTitle());
        //baseArticle.setPublishedDate(new Date().toString());
        baseArticle.setViews(1);
        baseArticle.setAuthorId(blogCreateRequest.getAuthorId());
        baseArticle.setContent(blogCreateRequest.getContent());
        //获取文章所属空间名
        String name = workspaceTreeMapper.findSpaceNameBySpaceId(blogCreateRequest.getSpaceId());
        baseArticle.setBelongsTo(name);
        baseArticle.setIsOriginal(blogCreateRequest.getIsOriginal()=="true"?1:0);
        baseArticle.setHasEnglishVersion(0);
        baseArticle.setCreatedAt(new Date());
        baseArticle.setUpdateAt(new Date());
        baseArticle.setLanguage(blogCreateRequest.getLanguage());
        baseArticle.setState("0");
        baseArticle.setSpace(blogCreateRequest.getSpaceId());


        articleMapper.addArticle(baseArticle);
    }

    @Override
    public DocumentVO getArticle(String articleId,String language) {
        BaseArticle baseArticle=new BaseArticle();
        baseArticle=articleMapper.getArticleById(articleId,language);
        List<BlogLinks> links=articleMapper.getLinks(articleId);
        for(BlogLinks blogLinks:links){

            blogLinks.setTitle(articleMapper.getLinkTitle(blogLinks.getLinkId()));
        }
        List<BlogTag> tags=articleMapper.getTags(articleId);
        for(BlogTag blogTag:tags){
            blogTag.setName(articleMapper.getTagName(blogTag.getTagId()));
        }
        Integer visibility=articleMapper.getVisibility(articleId);
        DocumentVO documentVO = new DocumentVO();
        UserDetails userDetails=userMapper.findUserDetailsByAccount(baseArticle.getAuthorId());
        userDetails.setAccount(null);
        userDetails.setPassword(null);
        documentVO.setBaseArticle(baseArticle);
        documentVO.setUserDetails(userDetails);
        documentVO.setLinks(links);
        documentVO.setTags(tags);
        documentVO.setVisibility(visibility);
        return documentVO;
    }


}
